package test;

import org.bouncycastle.openssl.PEMWriter;

import java.io.*;
import java.security.*;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.Base64;

public class GenPublicKeyFromPrivateKey {
    public static final String PRIVATE_KEY = "C:\\ideaprojects\\testencfile\\private.der";
    public static final String PUBLIC_KEY = "C:\\ideaprojects\\testencfile\\public.pem";

    private static void String2File(String fileName, String content) throws
            java.io.FileNotFoundException, java.io.IOException
    {
        File file = new File(fileName);

        BufferedWriter  writer  = new BufferedWriter (new FileWriter(file));

        writer.write(content);
        writer.close();
        return ;
    }

    private  static String rsaKeyToPEMFormat(Key key){
        StringWriter writer = new StringWriter();
        //org.bouncycastle.openssl.PEMWriter  bcprov-ext-jdk16-1.46.jar
        PEMWriter pemWriter = new PEMWriter(writer);
        try {
            pemWriter.writeObject(key);
            pemWriter.close();
            return writer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void main(String[] args) {
        File file = new File(PRIVATE_KEY);
        String inputFile = "C:\\ideaprojects\\testencfile\\dism.log";
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            DataInputStream dis = new DataInputStream(fis);

            byte[] keyBytes = new byte[(int) file.length()];
            dis.readFully(keyBytes);
            dis.close();

            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(spec);
            RSAPrivateCrtKey privk = (RSAPrivateCrtKey)privKey;
            System.out.println("Exponent :" + privKey.getPrivateExponent());
            System.out.println("Modulus" + privKey.getModulus());
            PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(privk.getModulus(), privk.getPublicExponent()));
            String2File(PUBLIC_KEY,rsaKeyToPEMFormat(publicKey));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
    }
}
